﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text.RegularExpressions;

public partial class Account : System.Web.UI.Page
{
    bool inputOK;

    protected void Page_Load(object sender, EventArgs e)
    {
        //Session["Account"] = Session["Userlogin"];
        //Session.Remove("Userlogin");
        if (!IsPostBack)
        {
            Label3.Visible = false;
            label2.Visible = false;

            this.Display();
            this.DisplayOrders();
        }
    }
    protected void Display()
    {
        DataTable dtb = new DataTable();
        dtb = (DataTable)Session["Userlogin"];
        if (dtb != null)
        {
            lblName.Text = dtb.Rows[0]["FullName"].ToString();
            txtName.Text = dtb.Rows[0]["FullName"].ToString();
            txtMail.Text = dtb.Rows[0]["Mail"].ToString();
            txtPhone.Text = dtb.Rows[0]["SDT"].ToString();
            txtAdd.Text = dtb.Rows[0]["DiaChi"].ToString();
        }
        else
        {
            lblName.Text = "";
            txtName.Text = "";
            txtMail.Text = "";
            txtPhone.Text = "";
            txtAdd.Text = "";
        }

    }
    protected void Edit_Click(object sender, EventArgs e)
    {
        DataTable dtb = new DataTable();
        dtb = (DataTable)Session["Userlogin"];
        if (dtb != null)
        {
            Check_Input();
            
            if (inputOK)
            {
                string id = dtb.Rows[0]["CustomerID"].ToString();
                string sql = string.Format(@"UPDATE customers 
                                             SET FullName = N'{0}', 
                                                Mail=N'{1}', 
                                                SDT= N'{2}', 
                                                DiaChi=N'{3}' 
                                             WHERE CustomerID=N'{4}'"
                                                ,txtName.Text, txtMail.Text
                                                ,txtPhone.Text,txtAdd.Text
                                                ,id);
                try
                {
                    DataBase.ExecuteNonQuery(sql);
                    this.refreshLoginSes(id);                    
                    lblError.Text = "Cập nhật thành công";
                }
                catch
                {
                    lblError.Text = "Cập nhật thất bại";
                }

            }
            
        }
        else
            lblError.Text = "Xin bạn hãy đăng nhập";
        //Response.Redirect("Account.aspx");

    }

    public void refreshLoginSes(string id)
    {
        String sql = @"SELECT * FROM customers WHERE CustomerID=@id";
        DataTable dt = DataBase.GetDataTable(sql, "@id", id);
        if (dt.Rows.Count > 0)
            Session["Userlogin"] = dt;
        //string path = HttpContext.Current.Request.Url.ToString();
        //Response.Redirect(path);
    }

    protected void Check_Input()
    {
        
        lblMailEx.Visible = Check_MailRegex(txtMail.Text) ? false : true;
        lblPhoneEx.Visible = Check_PhoneRegex(txtPhone.Text) ? false : true;
        //lblNote.Visible = Check_Email(txtMail.Text) ? false : true;
        lblEmailNotNull.Visible = Check_Null(txtMail.Text) ? false : true;
        lblNNull.Visible = Check_Null(txtPhone.Text) ? false : true;
        lblNotNull.Visible = Check_Null(txtName.Text) ? false : true;
        if (Check_Null(txtName.Text) && Check_Null(txtPhone.Text) && Check_Null(txtMail.Text)
            && Check_PhoneRegex(txtPhone.Text) && Check_MailRegex(txtMail.Text))
            inputOK = true;
        else inputOK = false;
    }
            
    
    protected bool Check_PhoneRegex(string input)
    {
        Regex myRegex = new Regex(@"^(0(\d{9)|\d{10})$");
        if (!myRegex.IsMatch(input))
            return false;
        else return true;
    }
    protected bool Check_MailRegex(string myString)
    {
        if (!Regex.IsMatch(myString, @"^(\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)$"))
            return false;
        else return true;
    }

    //protected bool Check_Email(string email)
    //{
    //    string sql2 = string.Format(@"select Mail From customers Where Mail='{0}'", email);
    //    DataTable dt2 = DataBase.GetDataTable(sql2);

    //    if (dt2.Rows.Count > 0)
    //        return false;
    //    else
    //    return true;
    //}
    protected bool Check_Null(string input)
    {
        if (string.IsNullOrEmpty(input))
            return false;
        else
            return true;
    }

    protected void DisplayOrders()
    {
        DataTable dtb = (DataTable)Session["Userlogin"];
        if (dtb != null)
        {
        


            string sql = "Select OrderID, NgayDat , NgayNhan , NoiNhan , TrangThai  From Orders Where CustomerID=@CustomerID And TrangThai=N'Đặt hàng' Order By NgayDat DESC";
            string CustomerID = dtb.Rows[0]["CustomerID"].ToString();
            DataTable Orders = DataBase.GetDataTable(sql, "@CustomerID", CustomerID);

            GridView1.DataSource = Orders;
            
            GridView1.DataBind();
            MutiView1.ActiveViewIndex = 0;
        }
        else lblError.Text = "Xin bạn hãy đăng nhập";
    }
    
    protected void Button1_Click(object sender, EventArgs e)
    {
        bool isPWOk = true;
        DataTable dtb = (DataTable)Session["Userlogin"];
        if (dtb != null)
        {
            if (txtCurPW.Text != dtb.Rows[0]["PassWord"].ToString())
            {
                isPWOk = false;
                Label1.Visible = true;
            }
            if (txtCurPW2.Text != txtCurPW.Text)
            {
                isPWOk = false;
                label2.Visible = true;
            }
            if (txtnewPW.Text == "")
            {
                isPWOk = false;
                Label3.Visible = true;
            }
            if (txtnewPW.Text != "" && txtCurPW.Text == dtb.Rows[0]["PassWord"].ToString() && txtCurPW2.Text == txtCurPW.Text)
                isPWOk = true;
            if (isPWOk)
            {
                try
                {
                    string CustomerID = dtb.Rows[0]["CustomerID"].ToString();
                    string sql = "Update customers Set PassWord=@PassWord Where CustomerID=@CustomerID";
                    DataBase.ExecuteNonQuery(sql, "@PassWord", txtnewPW.Text,
                        "@CustomerID", CustomerID);
                    lblError2.ForeColor = System.Drawing.Color.Green;
                    lblError2.Text = "Thay đổi mật khẩu thành công";

                }
                catch
                {
                    lblError2.ForeColor = System.Drawing.Color.Red;
                    lblError2.Text = "Thay đổi mật khẩu thất bại";
                }
            }

        }
        else
            lblError2.Text = "Xin bạn hãy đăng nhập";

    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void GridView1_SelectedIndexChanged1(object sender, EventArgs e)
    {
        
        
    }
    protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        int index = e.NewSelectedIndex;
        MutiView1.ActiveViewIndex = 1;
        string sql = string.Format(@"Select b.OrderID, a.TenXe  ,b.SoLuongMua,b.GiaBan 
                                     From ThongTinCoBan as a, OrderDetail as b 
                                     Where b.OrderID='{0}' and a.MaXe=b.MaXe",GridView1.Rows[index].Cells[2].Text);
        DataTable dtb = DataBase.GetDataTable(sql);
        GridView2.DataSource = dtb;
        GridView2.DataBind();
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        MutiView1.ActiveViewIndex = 0;
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int index = e.RowIndex;
        string sql = string.Format(@"Update Orders Set TrangThai=N'Hủy' Where OrderID='{0}'", GridView1.Rows[index].Cells[2].Text);
        string sqlchange = "INSERT INTO ThayDoi(OrderID,FullName,TrangThaiCu,TrangThaiMoi,NgayThayDoi) VALUES (@OrderID,@FullName,@TTCu,N'Hủy',@Time)";
        string sqlmodified = "UPDATE QuanTri SET Modified=1 WHERE Quyen='Admin'";

        DataBase.ExecuteNonQuery(sqlchange,"@OrderID", GridView1.Rows[index].Cells[2].Text
                                          ,"@FullName",lblName.Text
                                          ,"@TTCu",GridView1.Rows[index].Cells[6].Text
                                          ,"@Time",DateTime.Now);
        DataBase.ExecuteNonQuery(sql);
        DataBase.ExecuteNonQuery(sqlmodified);
        this.DisplayOrders();
    }
   
}